//获取博客列表
import {loadBlogList,deleteBlog, AuthManager } from "./common.js";
// 添加路由监听
let blogData=null;
init();
const bloglistPage=document.getElementById('bloglist');
const blogdetailPage=document.getElementById('blogdetail');
window.addEventListener('hashchange', handleRoute);
handleRoute(); // 初始化路由
function handleRoute() {
  const hash = window.location.hash.substring(1);
  
  if (hash.startsWith('blog-detail?blogid=')) {
    const blogid = hash.split('=')[1];
    if (blogData) {
      showBlogDetail(blogid);
    } else {
      // 数据未加载完成时的处理
      document.getElementById('det_title').innerHTML = '数据加载中...';
    }
  } else {
    // 显示列表页
    bloglistPage.style.display = 'block';
    blogdetailPage.style.display = 'none';
  }
};
async function init() {
  try {
    blogData = await loadBlogList();
    console.log('数据加载完成:', blogData);
    renderBlogList(blogData);
  } catch (error) {
    console.log('加载失败:', error);
  }
};
function renderBlogList(blogs)
{
const blogcontainer=document.getElementById('bloglist');

console.log(blogs.data.length);
    if(!blogs.data.length)
    {
        blogcontainer.innerHTML='<p>暂无博客内容<\p>';
        return;
    }
    // 使用模板字符串生成HTML
  const html = blogs.data.map(blog => `
  <div class="blog-card">
    <h2>${blog.title}</h2>
    <div class="meta">
      <span>作者：${blog.userid}</span>
      <span>日期：${new Date(blog.create).toLocaleDateString()}</span>
    </div>
    <p>${blog.content.slice(0, 100)}...</p>
    <a class="bloglink" data-blogid="${blog.blogid}" href="#blog-detail?blogid=${blog.blogid}" >阅读更多</a>
  </div>
`).join('');

// 5. 插入到容器
blogcontainer.innerHTML = html;
};

console.log(blogData);
function loadBlogContent(blogid)
{
  document.getElementById('det_title').innerHTML = '加载中...';
  const blog=blogData.data.find(item=>item.blogid===blogid);
  console.log(blog);
  if(blog)
  {
    document.getElementById('det_title').innerHTML=blog.title;
    document.getElementById('det_content').innerHTML=blog.content;
    document.getElementById('det_date').innerHTML=blog.create;
    document.getElementById('det_userid').innerHTML=blog.userid;
    document.getElementById('det_blogid').innerHTML=blog.blogid;
    

  }
  else
  {
    document.getElementById('det_title').innerHTML='博客为找到';
    
  }
};
function showBlogDetail(blogid)
{
  console.log('before');
  bloglistPage.style.display='none';
  blogdetailPage.style.display='block';
  console.log('after');
  loadBlogContent(blogid);
};
document.querySelectorAll('.bloglink').forEach(link =>{
  link.addEventListener('click',function(e){
    e.preventDefault();
    const blogId=this.dataset.blogid;
    console.log(blogId);
    //改变hash
    window.location.hash=`#blog-detail?blogid=${blogId}`;
  })
});
document.getElementById('back').addEventListener('click',function(){
  window.location.hash='';
});

// 删除按钮事件监听（正确写法）
document.getElementById('delete').addEventListener('click', async () => {
  try {
    // 1. 获取要删除的博客ID（假设存储在按钮的data-id属性中）
    const blogId = document.getElementById('det_blogid').innerText;
    
    // 2. 发送删除请求到后端
    await deleteBlog(blogId); // 返回Promise的异步函数
    
    // 3. 删除成功后导航到列表页
    window.location.href='/blog/blog_html/blog_home.html'
  } catch (error) {
    alert('删除失败：' + error.message);
  }
});

document.getElementById('out').addEventListener('click',out);
function out()
{
  if(confirm('你确定要退出吗?'))
  {
    AuthManager.clearToken();
    window.location.replace('/');
  }
}